<template>
  <n-layout class="h-[100vh]" content-class="flex flex-col">
    <LayoutHeader />
    <n-layout position="absolute" has-sider style="top: 70px">
      <n-layout-sider 
        :native-scrollbar="false" 
        bordered 
        collapse-mode="width" 
        :collapsed-width="64" 
        :width="216"
        :collapsed="isCollapse" 
        class="side-bar"
      >
        <n-menu 
          v-model:value="selectedKey" 
          :collapsed-width="64" 
          :collapsed-icon-size="22"
          :options="permissionStore.getBackMenuList" 
          key-field="path" 
          label-field="menuTitle"
          @update:value="handleUpdateValue" 
        />
      </n-layout-sider>
      <n-layout-content 
        :native-scrollbar="false" 
        content-class="p-2 h-full" 
        class="main-container scrollbar"
      >
        <router-view v-slot="{ Component, route }">
          <keep-alive v-if="openCache" :include="cachedViews">
            <component 
              :is="Component" 
              :key="route.meta?.keepAlive ? route.meta?.componentName || route.name : route.fullPath" 
            />
          </keep-alive>
          <component 
            v-else 
            :is="Component" 
            :key="route.fullPath" 
          />
        </router-view>
        <n-back-top :right="10" />
      </n-layout-content>
    </n-layout>
  </n-layout>
</template>
<script setup lang="ts">
import { watch, ref, computed } from "vue";
import LayoutHeader from "./header/index.vue";
import { useGlobalStore } from "@/store/modules/global.store";
import { storeToRefs } from "pinia";
import { usePermissionStore } from "@/store/modules/permission.store";
import { useRouter } from "vue-router";

const globalStore = useGlobalStore();
const permissionStore = usePermissionStore();
const router = useRouter();
const { isCollapse } = storeToRefs(globalStore);

const selectedKey = ref<string>("");

// 是否开启缓存
const openCache = computed(() => {
  // 检查当前路由是否需要缓存
  const currentRoute = router.currentRoute.value;
  return currentRoute.meta?.keepAlive === true;
});

// 计算需要缓存的组件名称列表
const cachedViews = computed(() => {
  if (!openCache.value) {
    return [];
  }
  return permissionStore.getCachedViews;
});

watch(
  () => router.currentRoute.value.fullPath,
  (newVal) => {
    if (newVal) {
      selectedKey.value = newVal;
    }
  },
  {
    immediate: true,
  }
);

const handleUpdateValue = (key: string) => {
  router.push(key);
};
</script>
<style scoped lang="scss">
@import "./index.scss";
</style>
